import {IS_FOR_WX, WX_CLOUD_DEV_ENV} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let PlayerData = require("PlayerData");
  let vibrate = require("./WechatVibrate");
  let bannerAd = require("./WechatBannerAd");
  let gameBanner = require("./WechatGameBanner");

  let isInited = false;
  let onShowRes = {
    query: {},
    referrerInfo: {}
  };
  
  let getOnShowRes = function () {
    return onShowRes;
  };
  
  wx.onShow((res) => {
    console.log('wx.onShow', res);
    onShowRes.scene = res.scene;
    onShowRes.query = res.query;
    onShowRes.shareTicket = res.shareTicket;
    onShowRes.referrerInfo = res.referrerInfo;
    vibrate.initVibrate();
    if (res.shareTicket === undefined) {
      let launchOption = wx.getLaunchOptionsSync();
      onShowRes.shareTicket = launchOption.shareTicket;
    }
    if (cc.CEventManager.instance) {
      cc.CEventManager.instance.dispatchEvent(EVENTS.GAME_ON_SHOW, res);
    }
  });
  
  let init = function () {
    if (isInited)
      return;
    if (Global.isDebug) {
      wx.cloud.init({
        traceUser: true,
        env: WX_CLOUD_DEV_ENV
      });
    } else {
      wx.cloud.init({traceUser: true});
    }
    
    
    wx.showShareMenu({withShareTicket: true});//显示转发菜单, 菜单中的“转发”选项默认不展示,设置分享按钮，方便获取群id展示群排行榜
    wx.onHide(() => {
      console.log('wx.onHide');
      if (PlayerData.instance.getUserId()) {
        PlayerData.instance.saveExitTime();
        PlayerData.instance.saveData(true);
      }
      if (cc.CEventManager.instance) {
        cc.CEventManager.instance.dispatchEvent(EVENTS.GAME_ON_HIDE);
      }
    });
    
    wx.aldOnShareAppMessage(function () {
      let shareInfo = Global.ShareWatchAdSwitch.defaultShareInfo;
      // 用户点击了“转发”按钮
      return {
        title: shareInfo.title,
        imageUrl: shareInfo.imageUrl
      }
    });
    
    bannerAd.initBannerAd();
    gameBanner.initGameBanner();

    isInited = true;
  };
  
  
  module.exports = {
    getOnShowRes,
    init,
  }
}